<template>
	<basic-container>
		<avue-crud :option="option" :data="data" ref="crud" v-model="form" :table-loading="loading" :permission="permissionList"
		 :before-open="beforeOpen" :page="page" @row-save="rowSave" @row-update="rowUpdate" @row-del="rowDel" @refresh-change="refreshChange"
		 @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange" @size-change="sizeChange"
		 @on-load="onLoad">
			<template slot-scope="{row,type,size}" slot="menu">
				<el-button :type="type" :size="size" icon="el-icon-thumb" @click="rowMenus(row)" v-has="'/mall-cloud-system/role/edit'">权限配置</el-button>
			</template>
		</avue-crud>
		<el-dialog title="权限配置" :visible.sync="box" width="90%">
<!--			:before-close="handleClose"-->
			<div class="tree-box">
				<el-scrollbar class="treescroll" style="height: 100%;max-height: 600px;overflow: auto;width: 190px;">
					<el-tree :data="menuTree" show-checkbox node-key="menuId" :check-strictly="false" ref="tree" highlight-current
					  @node-click="nodeClick" @check="menuChange" :props="{label:'name',value:'menuId',children:'children'}">
					</el-tree>
				</el-scrollbar>
				<avue-crud class="resourceTableData" ref="crud_res" :page="tablePage" :data="resourceTableData" :option="option4"
				 @current-change="tcurrentChange" @size-change="tsizeChange" @selection-change="selectionChange" @search-change="searchChange4">
				</avue-crud>
			</div>
			<span slot="footer">
				<el-button :disabled="isDisabled" type="primary" :loading="loadReplyBtn"  size="small" @click="handleSetRoles">确 定</el-button>
			</span>
		</el-dialog>
	</basic-container>
</template>

<script>
	import {
		getListdata,
		getRole,
		setMenu,
		add,
		update,
		remove
	} from "@/api/admin/roles";
	import {
		testSort
	} from '@/util/util';
	import {
		getMenuTree,
		getList
	} from '@/api/admin/menu'

	import {
		mapGetters
	} from "vuex";


	export default {
		data() {
			return {
				form: {},
				tempData:{},
				query: {},
				query4: {},
				currentMenuId: "",
				loading: true,
				isDisabled:false,
				loadReplyBtn:false,
				menuTree: [],
				menuKeys: [],
				resourceTableData: [],
				resourceKeys: [],
				box: false,
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				tablePage: {
					pageSize: 10,
					currentPage: 1,
					total: 0,
				},
				option: {
					size: 'mini',
					excelBtn: false,
					tip: false,
					border: true,
					index: true,
					selection: false,
					viewBtn: true,
					searchBtn: false,
					refreshBtn: false,
					columnBtn: false,
					height: 'auto',
					// calcHeight: 380,
					dialogType: 'dialog',
					rowKey: 'roleId',
					menuWidth: 300,
					align: 'center',
					searchMenuSpan:6,
					column: [{
							label: "名称",
							prop: "name",
							search: true,
							fixed: true,
							rules: [{
								required: true,
								message: "请输入名称",
								trigger: "blur"
							},
							{max: 10, message: '输入长度不得多于10个长度', trigger: 'blur'},
							]
						},
						{
							label: "别名",
							prop: "description",
							rules: [{
								required: true,
								message: "请输入别名",
								trigger: "blur"
							},
							{max: 10, message: '输入长度不得多于10个长度', trigger: 'blur'},
							]
						},
						{
							label: "排序",
							prop: "sort",
							rules: [{
								required: true,
								message: "请输入排序",
								trigger: "blur"
							}, {
								validator: testSort,
							}]
						}
					]
				},
				data: [],
				/**---dialog配置信息 ---**/
				option4: {
					searchBtn: true,
					menu: false,
					"refreshBtn": false,
					"columnBtn": false,
					border: true,
					editBtn: false,
					delBtn: false,
					calcHeight: "auto",
					height: 380,
					"addBtn": false,
					selection: true,
					/*selectable: (row, index) => {
					  return index === 1;
					},*/
					page: true,
					align: 'center',
					menuAlign: 'center',
					searchMenuSpan:6,
					column: [{
							label: '资源名称',
							prop: 'name',

						},
						{
							search: true,
							label: '路由地址',
							prop: 'url',

						},
						{
							label: '菜单编号',
							prop: 'code',

						}
					]
				},
			}
		},
		computed: {
			...mapGetters(["permission", 'userInfo']),
			permissionList() {
				return {
					addBtn: this.vaildData(this.permission["/mall-cloud-system/role/add"], false),
					delBtn: this.vaildData(this.permission["/mall-cloud-system/role/remove"], false),
					editBtn: this.vaildData(this.permission["/mall-cloud-system/role/edit"], false)
				};
			},
		},
		methods: {
			rowSave(e, loading, done) {
				add({
					pid: 0,
					...e
				}).then(res => {
					loading();
					if (res.data.code == 200) {
						//添加成功
						this.$message({
							type: "success",
							message: "添加成功!"
						});
						this.onLoad(this.page);
						done();
					}
				})
			},
			rowUpdate(e, loading, done) {
				update({
					pid: 0,
					...e
				}).then(res => {
					this.loading = true;
					if (res.data.code == 200) {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "修改成功!"
						});
						done();
					}
				})
			},
			rowDel(e) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(e.roleId);
					})
					.then(() => {
						if (this.data.length == 1) {
							this.page.currentPage -= 1
						}
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
					});

			},
			setCurrent() {
				let tempResource = [];
				this.resourceKeys.forEach(resid => {
					this.resourceTableData.forEach(row => {
						if (row.resourceId === resid) {
							tempResource.push(row);
						}
					});
				});
				//设置选中的行
				this.$refs.crud_res.toggleSelection(tempResource);
			},
			selectionChange(data) { //选中的数据
				this.resourceTableData.forEach(row => {
					this.resourceKeys = this.arrayRemoveKey(this.resourceKeys, row.resourceId);
				});
				data.forEach(row => {
					this.resourceKeys.push(row.resourceId);
				});

			},
			searchChange4(params,done) {
				this.query4 = params;
				this.query4["menuId"] = this.currentMenuId;
				this.loadRightResource(params,done);
			},
			arrayRemoveKey(array, key) {
				let _index = -1;
				array.forEach((item, index) => {
					if (item === key) {
						_index = index;
					}
				});
				if (_index != -1) {
					array.splice(_index, 1);
				}
				return array;
			},
			menuChange(data, checked) {
				console.log(checked)
				this.currentMenuId = data.menuId;
				this.resourceTableData = [];
				//1.检测当前菜单是否选中  true 选中 false 取消
				let isChecked = false;
				let checkedkeys = checked.checkedKeys
				let halfChecked = checked.halfCheckedKeys //半选中
				this.form.menuId = checkedkeys.concat(halfChecked)
				checked.checkedKeys.forEach(item => {
					if (item == data.menuId) {
						isChecked = true;
					}
				})
				this.query4["menuId"] = this.currentMenuId;
				//2.重新加载右侧资源列表
				getList(1, 100, this.query4).then(res => {
					if (res.status == 200) {
						this.resourceTableData = res.data.data
						//3. 步骤1如果true 设置资源全部选中   步骤1如果false 取消全选
						this.resourceTableData.forEach(row => {
							this.resourceKeys = this.arrayRemoveKey(this.resourceKeys, row.resourceId);
						});
						if (isChecked) {
							this.resourceTableData.forEach(row => {
								this.resourceKeys.push(row.resourceId);
							});
						}
						//4.重置右侧资源列表选中状态
						setTimeout(() => {
							this.setCurrent();
						}, 100)
					}
				})
			},
			//加载右侧资源列表
			loadRightResource(params = {},done) {
				this.resourceTableData = [];
				this.onLoad = true;
				//点击请求资源数据resource/setAuthority
				getList(this.tablePage.currentPage, this.tablePage.pageSize, this.query4).then(res => {
					if(done){
						done();
					}
					this.onLoad = false;
					if (res.status == 200) {
						const data = res.data;
						this.tablePage.total = data.count;
						this.resourceTableData = res.data.data
						setTimeout(() => {
							this.setCurrent();
						}, 100)
					}
				})
			},
			// 权限配置分页
			tcurrentChange(currentPage) {
				this.tablePage.currentPage = currentPage;
				this.loadRightResource();
			},
			tsizeChange(pageSize) {
				this.tablePage.pageSize = pageSize;
				this.loadRightResource();
			},
			nodeClick(data,b) { //点击菜单请求资源列表数据
				console.log(data);
				console.log(b);
				this.currentMenuId = data.menuId;
				this.query4["menuId"] = this.currentMenuId;
				this.tablePage.currentPage=1;
				this.tablePage.pageSize =10
				this.loadRightResource();

			},


			handleSetRoles() {
				// Array.from(new Set([...this.form.menuId,...this.$refs.tree.getHalfCheckedKeys()]))
				let data = {
					roleId: this.tempData.roleId,
					menuIds: [...this.$refs.tree.getHalfCheckedKeys(),...this.$refs.tree.getCheckedKeys()],
					resourceIds: this.resourceKeys
				}
				this.isDisabled = true;
				setMenu(data).then((res) => {
					if (res.status == 200) {
						this.$message.success('设置成功');
						this.box = false;
						// this.onLoad(this.page);
						location.reload();
					}
				})
			},


			handleClose(done) {
				location.reload();
			},

			rowMenus(row) { //触发点击权限配置请求数据
				this.tempData = row;
				this.isDisabled = false;
				getRole(this.tempData.roleId).then(res => { //根据角色获取菜单(roleId)
					console.log(res.data.data);
					this.box = true;
					this.tempData = res.data.data;
					this.tempData.menuId = this.tempData.menuIds || [];
					this.menuKeys = this.tempData.menuIds;
					this.resourceKeys = this.tempData.resourceIds || [];
					setTimeout(() => {
						this.$refs.tree.setCheckedKeys(this.menuKeys); //设置树结构默认选中
					}, 0)

				});
			},
			searchReset() {
				this.query = {};
				this.onLoad(this.page);
			},
			searchChange(params,done) {
				this.page.currentPage = 1;
				this.query = params;
				this.onLoad(this.page, params,done);
			},
			beforeOpen(done, type) {
				if (["edit", "view"].includes(type)) {
					getRole(this.form.roleId).then(res => {
						this.form = res.data.data;
					});
				}
				done();
			},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},
			refreshChange() {
				this.onLoad(this.page);
			},

			onLoad(page, params = {},done) { //页面初始化请求管理员列表
				this.loading = true;
				getListdata(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
					if(done){
						done();
					}
					this.res = false;
					const data = res.data;
					this.page.total = data.count;
					this.data = data.data
					this.loading = false;
				});
				getMenuTree().then(res => { //请求树结构
					this.menuTree = res.data.data;
				});
			},

		}
	};
</script>

<style scoped>
	.tree-box {
		width: 100%;
		height: 100%;
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
	}

	.resourceTableData {
		padding: 0 20px !important;
		flex: 10;
		width: calc(100% - 230px);
	}

	.avue-crud__menu {
		display: none;
	}

	.avue-crud__title {
		height: 50px !important;
		margin: 0 !important;
	}

	.treescroll {
		flex: 2;
	}
</style>
